<?php

class Util {

    public static function getExcerpt($str, $count = 50) {
        // remove html tags and &nbsp;
        $text = preg_replace('/(<.*?>|&nbsp;)/', "", $str);
        $arr = preg_split('/[\s]+/', $text);
        $len = count($arr);
        $excerpt = '';
        $hasMore = false;
        for ($i = 0; $i < $count && $i < $len; $i++) {
            $excerpt = $excerpt . $arr[$i] . ' ';
            if ($i == $count - 1 && $i < $len) {
                $hasMore = true;
            }
        }
        return array('excerpt' => trim($excerpt), 'hasMore' => $hasMore);
    }

    public static function getDigits($number, $count = 9) {
        // fill array with Os
        $digits = array_fill(0, $count, 0);

        for ($i = $count - 1; $i >= 0 && $number > 0; $i--) {
            $digits[$i] = $number % 10;
            $number /= 10;
        }

        return $digits;
    }

    /**
     * 
     */
    public static function getThumbnailImage($url, $size = array()) {
        // The '@' in front of getimagesize() suppresses error reporting for
        // that function. Alternatively, just use error_reporting(0);
        /* This function is reason to make slowly server. Skip for now */
        $_img = array();
        $_img['url'] = $url;
        $_img['width'] = $size[0];
        $_img['height'] = $size[1];
        return $_img;
        
        $img_info = @getimagesize($url);
        if (!$img_info) {
            echo '<!-- Image is missing. url: ', $url, ' -->';
            return false;
        }

        $_img = array();
        $_img['url'] = $url;
        list($_width, $_height) = $img_info;
        echo '<!-- Orginal size: width = ', $_width, ', height = ', $_height, '-->';
        if (count($size) == 2) {
            if ($_width > $size[0]) {
                $ratio = $size[0] / $_width;

                $_width = $size[0];
                $_height = floor($_height * $ratio);
            }
            if ($_height > $size[1]) {
                $ratio = $size[1] / $_height;

                $_width = floor($_width * $ratio);
                $_height = $size[1];
            }
        }
        $_img['width'] = $_width;
        $_img['height'] = $_height;
        return $_img;
    }

    public static function thumbnailImage($url, $size = array()) {
        $image = Util::getThumbnailImage($url, $size);
        if ($image) {
            echo '<img src="', $image['url'], '" />';
        }
    }

}
